import React, { Component } from 'react'
import { RouteChildrenProps } from 'react-router-dom'
import { Card, Form, Input, Button, Checkbox, message } from 'antd'
import logo from 'assets/login-header.png'
import { Logintype, loginToken } from 'api/contents/index'
import { setToken } from 'utils/storage'
import { login } from 'api/user/index'
import styles from './index.module.scss'

interface history extends RouteChildrenProps {}
export default class Login extends Component<history> {
  //登录
  onFinish = async (values: Logintype) => {
    const res = await login(values)
    console.log(res)
    const { data }: { data: loginToken } = res
    setToken(JSON.stringify(data))
    message.success('登录成功')
    const { state } = this.props.location as any
    //做鉴权判断
    if (state && state.fromPath) {
      this.props.history.push(state.fromPath)
    } else {
      this.props.history.push('/home')
    }
  }
  render() {
    return (
      <div className={styles.login}>
        <Card className="login-container">
          <img src={logo} className="logo" alt="" />
          <Form
            name="basic"
            size="large"
            onFinish={this.onFinish}
            validateTrigger={['onBlur', 'onChange']}
            initialValues={{
              mobile: '15900000000',
              code: '246810',
              agree: false,
            }}
          >
            <Form.Item
              name="mobile"
              rules={[
                {
                  required: true,
                  message: '请输入手机号',
                },
                {
                  pattern:
                    /^(0|86|17951)?(13[0-9]|15[012356789]|166|17[3678]|18[0-9]|14[57])[0-9]{8}$/,
                  message: '手机号不符合规范',
                },
              ]}
            >
              <Input />
            </Form.Item>
            <Form.Item
              name="code"
              rules={[
                {
                  required: true,
                  message: '请输入密码',
                },
                {
                  pattern: /^[0-9]{6}$/,
                  message: '密码格式不正确',
                },
              ]}
            >
              <Input.Password />
            </Form.Item>
            <Form.Item
              name="agree"
              valuePropName="checked"
              rules={[
                {
                  validator: (rule, value) =>
                    //console.log(rule, value),
                    value
                      ? Promise.resolve()
                      : Promise.reject(new Error('请勾选协议')),
                },
              ]}
            >
              <Checkbox>我已阅读并同意[用户协议]和[隐私条款]</Checkbox>
            </Form.Item>
            <Form.Item>
              <Button type="primary" htmlType="submit" block>
                Submit
              </Button>
            </Form.Item>
          </Form>
        </Card>
      </div>
    )
  }
}
